 express = require('express');
const mysql = require('mysql2/promise');
const cors = require('cors');
const app = express();

// 中间件
app.use(cors());
app.use(express.json());

// 数据库连接池
const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'water_management_system',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0
});

// 仪表板数据API
app.get('/api/dashboard', async (req, res) => {
    try {
        const [waterLevel] = await pool.query(
            'SELECT value FROM water_level_data ORDER BY recorded_at DESC LIMIT 1'
        );
        const [flowRate] = await pool.query(
            'SELECT value FROM flow_rate_data ORDER BY recorded_at DESC LIMIT 1'
        );
        
        res.json({
            waterLevel: waterLevel[0]?.value || 0,
            flowRate: flowRate[0]?.value || 0,
            weather: '晴 25°C' // 实际项目中应接入气象API
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({ error: '服务器错误' });
    }
});

// 启动服务器
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});
